//
//  SqliteManager.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 2016/10/10.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit

let dbPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("sinaWeibo.db")

class SqliteManager: NSObject {

    static let sharedManager: SqliteManager = SqliteManager()
    
    lazy var queue: FMDatabaseQueue = FMDatabaseQueue(path: dbPath)
    
    override init() {
        super.init()
        
        creatTable()
    }
    
    //  创建表
    private func creatTable() {
        
        let path = Bundle.main.path(forResource: "db.sql", ofType: nil)
        let sql = try! String(contentsOfFile: path!)
        queue.inDatabase { (db) in
            let result = db?.executeStatements(sql)
            if result! {
                print("建表成功")
            }else {
                print("建表失败")
            }
        }
    }
    
    func selectedDicArray(sql: String) -> [[String: Any]] {
        
        var tempArrayM = [[String: Any]]()
        
        queue.inDatabase { (db) in
            if let resultSet = db?.executeQuery(sql, withArgumentsIn: nil) {
                while resultSet.next() {
                    var dic = [String: Any]()
                    let colNum = resultSet.columnCount()
                    for i in 0..<colNum {
                        let colName = resultSet.columnName(for: i)
                        let colValue = resultSet.object(forColumnName: colName)
                        dic[colName!] = colValue
                    }
                    
                    tempArrayM.append(dic)
                }
            }
        }
        return tempArrayM
    }
    
}
